package com.dangdang.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.smartstruts.action.Action;
import org.smartstruts.action.ActionForm;

import com.dangdang.domain.ReceiveAddress;
import com.dangdang.domain.User;
import com.dangdang.service.ReceiveAddressService;
import com.dangdang.service.ServiceFactory;
import com.dangdang.service.UserService;
import com.dangdang.util.Constants;
import com.dangdang.util.FormUtils;
import com.dangdang.util.UUIDUtils;

/**
 * 用户注册综合控制类
 * 
 * @author Wangpeihu
 * @team [Never give up]
 * @since JDK1.6(建议)
 * @date 2010-1-18
 */
public class RegisterAction extends Action {
	UserService us = ServiceFactory.getUserService();
	ReceiveAddressService rs = ServiceFactory.getReceiveAddressService();

	/**
	 * 通用跳转方法<br>
	 * 当无须何种请求的时候,返回成功信号
	 * 
	 */
	@Override
	public String execute(ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		return Constants.FORWARD_SUCCESS;
	}

	/**
	 * 检测该邮箱是否已经存在
	 * 
	 * @param arg0
	 * @param arg1
	 * @param arg2
	 * @return
	 * @throws Exception
	 */
	public String checkEmail(ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// TODO
		return Constants.FORWARD_SUCCESS;
	}

	/**
	 * 邮箱验证码验证
	 * 
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public String verifyCode(ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// TODO
		return null;
	}

	/**
	 * 注册用户
	 * 
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public String registerValidate(ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("utf-8");
		User user = new User();
		FormUtils.populate(user, request);

		/** 随机产生验证码 */
		String emailVerifyCode = UUIDUtils.getUUID();
		user.setEmailVerifyCode(emailVerifyCode);

		if (null != user) {
			ReceiveAddress receiveAddress = FormUtils.populate(
					new ReceiveAddress(), request);
			User u = us.addUser(user);
			if (null != receiveAddress) {
				receiveAddress.setUserId(u);
				rs.addReceiveAddress(receiveAddress);
				HttpSession session = request.getSession();
				session.setAttribute(Constants.USER_KEY, u);
			}
			return Constants.FORWARD_SUCCESS;
		}
		return Constants.FORWARD_FAIL;
	}
}
